package com.itheima.health.common.aspect;

import com.itheima.health.common.BaseContext;
import com.itheima.health.common.annotation.Authority;
import com.itheima.health.common.pojo.UserInfo;
import com.itheima.health.exception.BusinessRuntimeException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class AuthorityAspect {


    @Pointcut("@annotation(com.itheima.health.common.annotation.Authority)")
    public void authorityPointCut() {

    }

    /**
     * 请求执行前
     */
    @Before(value = "authorityPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        Authority authority = getAnnotationLog(joinPoint);
        if (authority == null) {
            return;
        }
        UserInfo currentUser = BaseContext.getCurrentUser();
        boolean contains = currentUser.getAuthorities().contains(authority.values());
        if (!contains) {
            throw new BusinessRuntimeException("无访问权限");
        }
    }


    /**
     * 获取切点的log注解
     */
    private Authority getAnnotationLog(JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(Authority.class);
        }
        return null;
    }
}